package com.bootdo.system.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import ch.qos.logback.core.net.SyslogOutputStream;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.bootdo.common.utils.*;
import com.bootdo.system.dao.CategoryDao;
import com.bootdo.system.domain.CategoryDO;
import com.bootdo.system.domain.ProductInnerDO;
import com.bootdo.system.domain.ProjectDO;
import com.bootdo.system.service.CategoryService;
import com.bootdo.system.service.ProductInnerService;
import com.mysql.jdbc.MysqlDataTruncation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.system.domain.ProductDO;
import com.bootdo.system.service.ProductService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 产品
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2020-06-24 19:11:08
 */

@Controller
@RequestMapping("/system/product")
public class ProductController {

    @Value("${bootdo.uploadPath}")
    private String path;
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductInnerController productInnerController;
    @Autowired
    private ProductInnerService productInnerService;

    @GetMapping()
    @RequiresPermissions("system:product:product")
    String Product(Model model) {

        List<CategoryDO> categorys = categoryService.list(null);
        CategoryDO categoryDO = new CategoryDO();
        categoryDO.setCategoryName("没有分类");
        categoryDO.setCategoryId(-1);

        categorys.add(0, categoryDO);

        model.addAttribute("categorys", categorys);

        List<ProductDO> products = productService.listallDistinct();


        return "system/product/product";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("system:product:product")
    public PageUtils list(@RequestParam Map<String, Object> params, Map<String, Object> map) {
        System.out.println("product lis的参数=" + params);

        Object categoryId = params.get("categoryId");
        if (categoryId.toString().trim().equals("-1")) {
            params.remove("categoryId");
        }
        Object level2Cate = params.get("level2Cate");
        if (level2Cate.toString().trim().equals("2.没有二级")) {
            params.remove("level2Cate");
        }
        Object brand = params.get("brand");
        if (brand.toString().trim().equals("3.没有品牌")) {
            params.remove("brand");
        }
        Object productNum = params.get("productNum");
        if (productNum.toString().trim().equals("4.没有编号")) {
            params.remove("productNum");
        }


        //查询列表数据
        Query query = new Query(params);
        List<ProductDO> productList = productService.list(query);

        int total = productService.count(query);
        System.out.println("项目数据库的总数=" + total + " 计算的size是=" + productList.size());
        PageUtils pageUtils = new PageUtils(productList, total);


        return pageUtils;
    }

    @Transactional
    @RequestMapping("/uploadexcel")
    @ResponseBody
    @RequiresPermissions("system:product:uploadexcel")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)
            throws IllegalStateException, IOException {

        // 判断文件是否为空，空则返回失败页面
        if (file.isEmpty()) {
            return "不可以上传空文件";
        }
        System.out.println("原始文件名=" + file.getOriginalFilename() + "-" + file.getOriginalFilename().toLowerCase().toString().endsWith(".xls"));
        if (!file.getOriginalFilename().toLowerCase().toString().endsWith(".xls")) {
            if (!file.getOriginalFilename().toLowerCase().toString().endsWith(".xlsx")) {
                return "失败，请检查文件格式";
            }
        }


        // 获取原文件名
        String fileName = file.getOriginalFilename();
        // 创建文件实例
        File filePath = new File(path, System.currentTimeMillis() + fileName);
        // 如果文件目录不存在，创建目录
        if (!filePath.getParentFile().exists()) {
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录" + filePath);
        }
        // 写入文件
        file.transferTo(filePath);

        // 2.应用HUtool ExcelUtil获取ExcelReader指定输入流和sheet
        ExcelReader excelReader = ExcelUtil.getReader(filePath);
        // 可以加上表头验证
        System.out.println("读取excel开始");
        // 3.读取第二行到最后一行数据
        List<List<Object>> read = excelReader.read(1, excelReader.getRowCount());
        String result = " 消息：";
        final int size = Integer.MAX_VALUE;
        ArrayList<Object> successsave = new ArrayList<>();
        for (List<Object> objects : read) {
            try {


                System.out.println("读取excel=" + objects + "总长度=" + size);
                ProductDO productDO = new ProductDO();

                if (size > 0) {

                    Object fenleiId = objects.get(0);
                    if (fenleiId == null) {
                        fenleiId = 1;
                    }
                    CategoryDO categoryDO = categoryService.get(Integer.parseInt(fenleiId.toString()));
                    if (categoryDO == null) {
                        result += " - 分类id填写错误";
                        continue;
                    }
                    if (!StringUtils.isEmpty(fenleiId.toString()) && categoryDO != null) {
                        productDO.setCategoryId(Integer.parseInt(fenleiId.toString()));
                    }
                }

                if (size > 1) {
                    Object productNum = objects.get(1);
                    if (!StringUtils.isEmpty(productNum.toString())) {
                        productDO.setProductNum((String) productNum);
                    }
                }
                if (size > 2) {
                    Object shebeiName = objects.get(2);
                    if (!StringUtils.isEmpty(shebeiName.toString())) {
                        productDO.setShebeiName((String) shebeiName);
                    }
                }

                if (size > 3) {
                    Object basicParam = objects.get(3);
                    if (basicParam != null) {
                        productDO.setBaseParam(basicParam.toString().trim());
                    }
                }
                if (size > 4) {
                    Object allParam = objects.get(4);
                    if (!StringUtils.isEmpty(allParam.toString())) {
                        productDO.setAllParam(allParam.toString().trim());
                    }
                }
                if (size > 5) {
                    Object unit = objects.get(5);
                    if (!StringUtils.isEmpty(unit.toString()))
                        productDO.setUnit(unit.toString());
                }

                //面价
                if (size > 6) {
                    Object facePrice = objects.get(6);
                    if (facePrice != null) {
                        productDO.setFacePrice(Double.parseDouble(facePrice.toString().trim()));
                    }
                }
                //成本
                if (size > 7) {
                    Object chengben = objects.get(7);
                    if (chengben != null)
                        productDO.setChengben(Double.parseDouble(chengben.toString().trim()));
                }
                //设备成本
                if (size > 8) {
                    Object shebei_chengben = objects.get(8);
                    if (shebei_chengben != null)
                        productDO.setShebeiChengben(Double.parseDouble(shebei_chengben.toString().trim()));
                }
                //安装成本
                if (size > 9) {
                    Object anzhuang_chengben = objects.get(9);
                    if (anzhuang_chengben != null)
                        productDO.setAnzhuangChengben(Double.parseDouble(anzhuang_chengben.toString().trim()));
                }

                if (size > 10) {
                    Object level2_cat = objects.get(10);
                    if (level2_cat != null)
                        productDO.setLevel2Cate((String) level2_cat);

                }
                if (size > 11) {
                    Object brand = objects.get(11);
                    if (brand != null)
                        productDO.setBrand(brand.toString().trim());
                }
                if (size > 12) {
                    Object xinghao = objects.get(12);
                    if (xinghao != null)
                        productDO.setXinghao(xinghao.toString().trim());
                }
                if (size > 13) {
                    Object beizhu = objects.get(13);
                    if (beizhu != null)
                        productDO.setBeizhu(beizhu.toString().trim());
                }
                try {
                    productService.save(productDO);
                } catch (Exception e){
                    e.printStackTrace();
                    System.out.println("上传文件失败"+e.getMessage());
                    result += " 提示： 保存当前项失败，请检查文件格式  ";
                }

                successsave.add(productDO.getShebeiName());

            } catch (NullPointerException e) {
                result += "  存在空值异常，请将空的单元格设置上一个值，再次尝试。  【之前正确的数据已经保存】包括：" + successsave;
                e.printStackTrace();
                return result;
            } catch (ClassCastException e) {
                result += "  格式转化失败，请检查数值，再次尝试  【之前正确的数据已经保存】包括：" + successsave;
                e.printStackTrace();
                return result;
            } catch (NumberFormatException e) {
                result += " 1. 存在空字符串异常，请将空的单元格设置上一个值，2.数值无法转换，请检查数值，再次尝试。  【之前正确的数据已经保存】包括：" + successsave;
                e.printStackTrace();
                return result;
            } catch (IndexOutOfBoundsException e) {
                result += "  表格存在空串，请将空的单元格设置上一个值，再次尝试。  【之前正确的数据已经保存】包括：" + successsave;
                e.printStackTrace();
                return result;
            }catch (Exception e){
                e.printStackTrace();
                result+="表格格式错误，请检查excel文件";
            }
        }
        String filename = new String(file.getOriginalFilename());
        return result + "  " + filename + "，上传文件成功";
    }

    @GetMapping("/add")
    @RequiresPermissions("system:product:add")
    String add(Model model) {
        List<CategoryDO> list = categoryService.list(null);

        model.addAttribute("categorys", list);
        return "system/product/add";
    }

    @ResponseBody
    @RequestMapping("/getaggresult")
    public R getAggRestlt(ProductDO projectDO) {

        Integer categoryId = projectDO.getCategoryId();
        if (categoryId == null) {
            projectDO.setCategoryId(-1);
            categoryId = -1;
        }
        if (categoryId == -1) {
            projectDO.setCategoryId(null);
        }
        String level2Cate = projectDO.getLevel2Cate();
        if (level2Cate.toString().trim().equals("2.没有二级")) {
            projectDO.setLevel2Cate(null);
        }
        String brand = projectDO.getBrand();
        if (brand.trim().equals("3.没有品牌")) {
            projectDO.setBrand(null);
        }
        String productNum = projectDO.getProductNum();
        if (productNum.toString().trim().equals("4.没有编号")) {
            projectDO.setProductNum(null);
        }

        List<ProductDO> list = productService.getAggRestlt(projectDO);

        HashSet<String> level2Cates = new HashSet<>();
        level2Cates.add("2.没有二级");
        HashSet<String> brands = new HashSet<>();
        brands.add("3.没有品牌");
        HashSet<String> productNums = new HashSet<>();
        productNums.add("4.没有编号");
        for (ProductDO product : list) {
            level2Cates.add(org.apache.commons.lang3.StringUtils.isEmpty(product.getLevel2Cate()) ? "2.没有二级" : product.getLevel2Cate());
            brands.add(org.apache.commons.lang3.StringUtils.isEmpty(product.getBrand()) ? "3.没有品牌" : product.getBrand());
            productNums.add(org.apache.commons.lang3.StringUtils.isEmpty(product.getProductNum()) ? "4.没有编号" : product.getProductNum());
        }


        return R.ok().put("level2Cates", level2Cates).put("brands", brands).put("productNums", productNums);
    }

    @GetMapping("/edit/{productId}")
    @RequiresPermissions("system:product:edit")
    String edit(@PathVariable("productId") Integer productId, Model model) {
        ProductDO product = productService.get(productId);
        model.addAttribute("product", product);

        List<CategoryDO> list = categoryService.list(null);

        model.addAttribute("categorys", list);
        return "system/product/edit";
    }

    @ResponseBody
    @GetMapping("/get/{productId}")
    R getProductJson(@PathVariable("productId") Integer productId) {
        ProductDO product = productService.get(productId);
        if (product == null) {
            return R.error("该产品ID不存在，请检查重试");
        }

        double onechengben = product.getAnzhuangChengben() + product.getShebeiChengben() + product.getChengben();
        return R.ok().put("baojia", MyUtils.getDouble2(onechengben * 2));
    }


    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:product:add")
    public R save(ProductDO product) {


        if (productService.save(product) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Transactional
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:product:edit")
    public R update(ProductDO product) {
        productService.update(product);
        HashMap<String, Object> map = new HashMap<>();
        map.put("productId", product.getProductId());

        List<ProductInnerDO> list = productInnerService.list(map);
        for (ProductInnerDO productInnerDO : list) {
            productInnerController.getSonsysMoney(productInnerDO.getSonsysId());
        }


        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:product:remove")
    public R remove(Integer productId) {
        try {
            if (productService.remove(productId) > 0) {
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(444, "项目正在引用这个产品，不可删除。");
        }

        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:product:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] productIds) {
        try {
            productService.batchRemove(productIds);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(444, "有项目正在引用这个产品，不可删除。");
        }

        return R.ok();
    }

}
